<template>
  <div class="user-manager-page">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
      </a-form-item>
      <a-form-item label="用户角色">
        <a-select
          v-model:value="searchParams.userRole"
          placeholder="选择用户角色"
          allow-clear
        >
          <a-select-option value="admin">管理员</a-select-option>
          <a-select-option value="user">普通用户</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="default" @click="resetHandle">重置</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>

        <div style="flex: 1" />
      <a-form-item>
        <div>
          <a-button type="primary" @click="handleCreate">
            <PlusOutlined />
            创建用户
          </a-button>
        </div>
      </a-form-item>
    </a-form>
    <a-divider />

    <!-- 表格 -->
    <a-card class="table-card">
      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="false"
          :loading="loading"
          :scroll="{ y: 420, x: 1200 }"
          :row-class-name="(_, index) => index % 2 === 0 ? 'even-row' : 'odd-row'"
        >
          <template #bodyCell="{ column, record }">
            <!-- 头像列 -->
            <template v-if="column.dataIndex === 'userAvatar'">
              <a-avatar :src="record.userAvatar" :size="32">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </template>

            <!-- 用户角色列 -->
            <template v-else-if="column.dataIndex === 'userRole'">
              <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
                {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
              </a-tag>
            </template>

            <!-- 创建时间列 -->
            <template v-else-if="column.dataIndex === 'createTime'">
              {{formatDateTime(record.createTime)  }}
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <div class="action-group">
                <a-button type="link" size="small" @click="handleView(record)">
                  <EyeOutlined />
                  查看
                </a-button>
                <a-divider type="vertical" />
                <a-button type="link" size="small" @click="handleEdit(record)">
                  <EditOutlined />
                  编辑
                </a-button>
                <a-divider type="vertical" />
                <a-button type="link" size="small" danger @click="showDeleteConfirm(record)">
                  <DeleteOutlined />
                  删除
                </a-button>
                <a-divider type="vertical" />
                <a-dropdown>
                  <a-button type="link" size="small">
                    <MoreOutlined />
                    更多
                    <DownOutlined />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="handleResetPassword(record)">
                        <KeyOutlined />
                        重置密码
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="currentPageSize"
          :total="Number(total)"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :show-total="(total) => `共 ${total} 条数据`"
          :page-size-options="pageSizeOptions"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
        />
      </div>
    </a-card>

    <!-- 查看用户弹窗 -->
    <a-modal
      v-model:open="viewModalVisible"
      title="查看用户"
      width="600px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="ID">{{ currentUser?.id }}</a-descriptions-item>
        <a-descriptions-item label="账号">{{ currentUser?.userAccount }}</a-descriptions-item>
        <a-descriptions-item label="用户名">{{ currentUser?.userName }}</a-descriptions-item>
        <a-descriptions-item label="用户角色">
          <a-tag :color="currentUser?.userRole === 'admin' ? 'red' : 'blue'">
            {{ currentUser?.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="简介" :span="2">{{ currentUser?.userProfile }}</a-descriptions-item>
        <a-descriptions-item label="头像" :span="2">
          <a-avatar :src="currentUser?.userAvatar" :size="64">
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ formatDateTime(currentUser?.createTime) }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 创建/编辑用户弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      :title="isEdit ? '编辑用户' : '创建用户'"
      width="600px"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        layout="vertical"
      >
        <a-form-item label="账号" name="userAccount" v-if="!isEdit">
          <a-input v-model:value="editForm.userAccount" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="密码" name="userPassword" v-if="!isEdit">
          <a-input-password v-model:value="editForm.userPassword" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="确认密码" name="checkPassword" v-if="!isEdit">
          <a-input-password v-model:value="editForm.checkPassword" placeholder="请确认密码" />
        </a-form-item>
        <a-form-item label="用户角色" name="userRole">
          <a-select v-model:value="editForm.userRole">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="简介" name="userProfile">
          <a-textarea v-model:value="editForm.userProfile" :rows="4" placeholder="请输入简介" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认弹窗 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="删除确认"
      @ok="handleDeleteConfirm"
      @cancel="handleDeleteCancel"
    >
      <p>确定要删除用户 "{{ deleteRecord?.userName }}" 吗？</p>
      <p style="color: #ff4d4f">此操作不可恢复！</p>
    </a-modal>

    <!-- 重置密码弹窗 -->
    <a-modal
      v-model:open="resetPasswordModalVisible"
      title="重置密码"
      @ok="handleResetPasswordSubmit"
      @cancel="handleResetPasswordCancel"
    >
      <a-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        layout="vertical"
      >
        <a-form-item label="新密码" name="userPassword">
          <a-input-password v-model:value="resetPasswordForm.userPassword" placeholder="请输入新密码" />
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  DownOutlined,
  UserOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  KeyOutlined,
  TeamOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import {
  deleteUser,
  listUserVoByPage,
  updateUser,
  addUser,
  resetUserPasswordById
} from "@/api/userController"
import { message } from "ant-design-vue"
import {formatDateTime} from "@/utils/dateUtils.ts"
import {SortEnum} from "@/constants"

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    width: 150,
    ellipsis: true
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    width: 120,
    ellipsis: true
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    width: 100,
    align: 'center'
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    width: 200,
    ellipsis: true
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right'
  }
]

// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)
const loading = ref(false)

// 分页配置
const currentPage = ref(1)
const currentPageSize = ref(5)
const pageSizeOptions = ['5', '10', '20', '50', '100']

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 5,
  userAccount: '',
  userName: '',
  userRole: undefined,
  sortField: 'createTime',
  sortOrder: SortEnum.DESCEND
})

// 弹窗状态
const viewModalVisible = ref(false)
const editModalVisible = ref(false)
const deleteModalVisible = ref(false)
const resetPasswordModalVisible = ref(false)
const assignRoleModalVisible = ref(false)
const editFormRef = ref()
const resetPasswordFormRef = ref()
const assignRoleFormRef = ref()
const currentUser = ref<API.UserVO>()
const deleteRecord = ref<API.UserVO>()
const resetRecord = ref<API.UserVO>()
const assignRoleRecord = ref<API.UserVO>()
const isEdit = ref(false)

// 编辑表单
const editForm = reactive<API.UserVO>({
  id: undefined,
  userAccount: '',
  userName: '',
  userRole: 'user',
  userProfile: '',
  userAvatar: '',
  createTime: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  userPassword: '',
  checkPassword: ''
})

// 分配角色表单
const assignRoleForm = reactive({
  userRole: 'user'
})

// 验证两次输入密码是否一致（Promise形式）
const validateCheckPassword = async (rule: any, value: string): Promise<void> => {
  if (value && value !== editForm.userPassword) {
    throw new Error('两次输入密码不一致')
  }
}

// 验证重置密码两次输入是否一致（Promise形式）
const validateResetPassword = async (rule: any, value: string): Promise<void> => {
  if (value && value !== resetPasswordForm.userPassword) {
    throw new Error('两次输入密码不一致')
  }
}

// 编辑表单验证规则
const editRules = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于 8 位', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateCheckPassword }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  userProfile: [
    { max: 200, message: '简介最多 200 个字符', trigger: 'blur' }
  ]
}

// 重置密码表单验证规则
const resetPasswordRules = {
  userPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于 8 位', trigger: 'blur' }
  ],
}

// 分配角色表单验证规则
const assignRoleRules = {
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    searchParams.pageNum = currentPage.value
    searchParams.pageSize = currentPageSize.value

    const res = await listUserVoByPage(searchParams)
    if (res.data.code === 0 && res.data.data) {
      data.value = res.data.data.records || []
      total.value = res.data.data.totalRow || 0
    } else {
      message.error("获取数据失败," + res.data.message)
    }
  } catch (error) {
    message.error("获取数据失败")
  } finally {
    loading.value = false
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页处理
const handlePageChange = async (page: number) => {
  currentPage.value = page
  await fetchData()
}

const handleSizeChange = async (current: number, size: number) => {
  currentPage.value = 1
  currentPageSize.value = size
  await fetchData()
}

// 条件搜索数据
const doSearch = async () => {
  searchParams.pageNum = 1
  currentPage.value = 1
  await fetchData()
}

// 重置
const resetHandle = async () => {
  searchParams.pageNum = 1
  currentPage.value = 1
  searchParams.userAccount = ''
  searchParams.userName = ''
  searchParams.userRole = undefined
  await fetchData()
}

// 创建用户
const handleCreate = () => {
  isEdit.value = false
  editForm.id = undefined
  editForm.userAccount = ''
  editForm.userName = ''
  editForm.userPassword = ''
  editForm.checkPassword = ''
  editForm.userRole = 'user'
  editForm.userProfile = ''
  editForm.userAvatar = ''
  editForm.createTime = ''
  editModalVisible.value = true
}

// 查看用户
const handleView = (record: API.UserVO) => {
  currentUser.value = { ...record }
  viewModalVisible.value = true
}

// 编辑用户
const handleEdit = (record: API.UserVO) => {
  isEdit.value = true
  editForm.id = record.id
  editForm.userAccount = record.userAccount
  editForm.userName = record.userName
  editForm.userPassword = ''
  editForm.checkPassword = ''
  editForm.userRole = record.userRole
  editForm.userProfile = record.userProfile
  editForm.userAvatar = record.userAvatar
  editForm.createTime = record.createTime
  editModalVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    await editFormRef.value?.validate()
    if (isEdit.value) {
      // 编辑用户
      const res = await updateUser(editForm)
      if (res.data.code === 0) {
        message.success('更新成功')
        editModalVisible.value = false
        await fetchData()
      } else {
        message.error('更新失败,' + res.data.message)
      }
    } else {
      // 创建用户
      const res = await addUser(editForm)
      if (res.data.code === 0) {
        message.success('创建成功')
        editModalVisible.value = false
        await fetchData()
      } else {
        message.error('创建失败,' + res.data.message)
      }
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 取消编辑
const handleEditCancel = () => {
  editFormRef.value?.resetFields()
  editModalVisible.value = false
}

// 显示删除确认
const showDeleteConfirm = (record: API.UserVO) => {
  deleteRecord.value = record
  deleteModalVisible.value = true
}

// 确认删除
const handleDeleteConfirm = async () => {
  if (!deleteRecord.value?.id) return

  try {
    const res = await deleteUser({ id: deleteRecord.value.id })
    if (res.data.code === 0) {
      message.success('删除成功')
      deleteModalVisible.value = false
      await fetchData()
    } else {
      message.error('删除失败,' + res.data.message)
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 取消删除
const handleDeleteCancel = () => {
  deleteModalVisible.value = false
  deleteRecord.value = undefined
}

// 重置密码
const handleResetPassword = (record: API.UserVO) => {
  resetRecord.value = record
  resetPasswordForm.userPassword = ''
  resetPasswordModalVisible.value = true
}

// 提交重置密码
const handleResetPasswordSubmit = async () => {
  try {
    await resetPasswordFormRef.value?.validate()
    const res = await resetUserPasswordById({
      userId: resetRecord.value?.id,
      newUserPassword: resetPasswordForm.userPassword
    })
    if (res.data.code === 0) {
      message.success('密码重置成功')
      resetPasswordModalVisible.value = false
      await fetchData()
    } else {
      message.error('密码重置失败,' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 取消重置密码
const handleResetPasswordCancel = () => {
  resetPasswordFormRef.value?.resetFields()
  resetPasswordModalVisible.value = false
  resetRecord.value = undefined
}

// 取消分配角色
const handleAssignRoleCancel = () => {
  assignRoleFormRef.value?.resetFields()
  assignRoleModalVisible.value = false
  assignRoleRecord.value = undefined
}
</script>

<style scoped>
.user-manager-page {
  padding: 24px;
  background: #f0f2f5;
  height: calc(100vh - 180px);
  flex-direction: column;
  min-width: 700px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
}

.table-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

:deep(.ant-table) {
  border-radius: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #1a1a1a;
  position: sticky;
  top: 0;
  z-index: 1;
}

:deep(.ant-table-tbody > tr.even-row) {
  background-color: #fafafa;
}

:deep(.ant-table-tbody > tr.odd-row) {
  background-color: #fff;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

.action-group {
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
}

:deep(.ant-btn-link) {
  padding: 0 4px;
}

:deep(.ant-btn-sm) {
  height: 24px;
  padding: 0 4px;
  font-size: 12px;
}

:deep(.ant-divider-vertical) {
  height: 14px;
  margin: 0 4px;
}

:deep(.ant-dropdown-trigger) {
  padding: 0 4px;
}

:deep(.ant-avatar) {
  border-radius: 50%;
}

:deep(.ant-tag) {
  min-width: 60px;
  text-align: center;
}

.pagination-container {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}

:deep(.ant-table-container) {
  overflow-x: auto;
}

:deep(.ant-table-body) {
  overflow-x: auto !important;
}

:deep(.ant-table-cell) {
  padding: 12px 8px;
}

:deep(.ant-table-cell-fix-right::before) {
  box-shadow: inset -10px 0 8px -8px rgba(0, 0, 0, 0.15);
}

:deep(.ant-table-cell-fix-left::before) {
  box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.15);
}

:deep(.ant-pagination) {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

:deep(.ant-pagination-item) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  margin: 0 4px;
}

:deep(.ant-pagination-prev),
:deep(.ant-pagination-next) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  margin: 0 4px;
}

:deep(.ant-pagination-jump-prev),
:deep(.ant-pagination-jump-next) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  margin: 0 4px;
}

:deep(.ant-pagination-options) {
  margin-left: 16px;
}

:deep(.ant-pagination-options-size-changer) {
  height: 32px;
  margin-right: 8px;
}

:deep(.ant-select) {
  min-width: 120px;
}

:deep(.ant-descriptions-item-label) {
  width: 100px;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-form-item-label) {
  padding-bottom: 4px;
}
</style>
